Asymptotically optimal algorithm